
import createPlotRenderComponent from './createPlotRenderComponent.jsx'
import omit from 'mars-pro/src/pro/omit.js'
const plots = {}

const BIZTYPE_ANONYMOUS = 'anonymous-type'
const BIZNAME_ANONYMOUS = 'anonymous-name'

function addPlot(bizType, bizName, desc, option) {
    bizType = bizType || BIZTYPE_ANONYMOUS
    bizName = bizName || BIZNAME_ANONYMOUS

    if (!plots[bizType]) {
        plots[bizType] = []
    }
    plots[bizType].push({ bizType, bizName, option, desc })
}

export function resolveBaseChartScopeSlot(scopeSlot) {
    scopeSlot = scopeSlot || {}
    return Object.keys(scopeSlot).reduce((m, key) => {
        m[key] = (...args) => {
            if (scopeSlot[key]) {
                return scopeSlot[key](...args)
            }
        }
        return m
    }, {})
}

/**
 * @param {*} bizType 业务类型 
 * @param {*} bizName 
 * @param {*} option 
 */
export function gen(bizType, bizName, desc, option) {
    if (!option || typeof option.render !== 'function') {
        return
    }
    addPlot(bizType, bizName, desc, option)
    const PlotRenderComponent = createPlotRenderComponent(option)
    return {
        name: option.name,
        componentName: option.name,
        functional: true,
        render(h, { data, props, children, scopedSlots, slots }) {
            const userSlots = slots()
            const _data = {
                ...data,
                props: {
                    ...(data.attrs),
                    ...(props),
                    plotOption: option
                },
                attrs: {
                    ...(data.attrs),
                    ...(props)
                },
                scopedSlots: resolveBaseChartScopeSlot(omit(scopedSlots, Object.keys(userSlots)))
            }
            slots = omit(slots, ['default'])
            return (
                <PlotRenderComponent {..._data}>
                    {
                        Object.keys(userSlots).map((item) => (
                            <template slot={item}>{userSlots[item]}</template>
                        ))
                    }
                </PlotRenderComponent>
            )
        }
    }
}

export function getPlots(){
    return plots
}
